package org.example.web;

import lombok.extern.slf4j.Slf4j;
import org.example.feign.CocosFeignClient;
import org.example.service.StudentHeartbeatService;
import org.example.util.HeartbeatScheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

@RestController
@Slf4j
public class CocosConfigController {
    @Resource
    CocosFeignClient cocosFeignClient;
    @Autowired
    HeartbeatScheduler heartbeatScheduler;
    @Autowired
    private StudentHeartbeatService heartbeatService;     //web

    @PostMapping("/api/upload-cocos-config")
    @CrossOrigin("*")
    public String uploadConfig(@RequestParam("cocosConfigFile") MultipartFile file) {
        try {
            // 执行文件传输
            String result = cocosFeignClient.forwardFile(file);
            log.info("Feign调用结果: {}", result);

            // 无论文件传输成功或失败，都停止心跳
            try {
                heartbeatService.disconnect();
                log.info("文件传输完成，已断开心跳和STOMP连接");
            } catch (Exception e) {
                log.error("断开心跳连接失败", e);
            }

            // 根据结果返回不同的响应
            if (result.contains("文件处理成功")) {
                return "上传成功";
            } else {
                return "上传请求已接收，正在处理中";
            }
        } catch (Exception e) {
            log.error("上传失败", e);
            return "处理失败: " + e.getMessage();
        }
    }
}
